package com.flycms.web.oauth;

import com.alibaba.fastjson.JSONObject;
import com.flycms.module.user.model.User;
import com.flycms.module.user.service.UserRestService;
import com.flycms.module.user.utils.UserSessionUtils;
import com.flycms.utils.HttpClient;
import com.flycms.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * @author huangzt
 * @version 1.0
 * @date 2020/9/17 15:14
 */
@Controller
@Slf4j
public class OauthController {

    @Autowired
    private UserRestService userService;
    @Autowired
    private UserSessionUtils userSessionUtils;

    @Value("${web-redirect}")
    private String webRedirect;

    @Value("${redirectUri}")
    private String redirectUri;

    @RequestMapping("/flycms/OAuth/login")
    public void oAuthLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "https://auth.ms.casicloud.com/1/oauth/authorize?client_id=" + SignUtil.CLIENT_ID
                + "&redirect_uri=" + redirectUri + "&response_type=code";
        User user = UserSessionUtils.getLoginMember(request);
        if (user != null) {
            response.sendRedirect(webRedirect);
        } else {
            response.sendRedirect(url);
        }
    }

    /**
     * 回调接口
     * 
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/flycms/OAuth/code")
    @ResponseBody
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sign = SignUtil.signQuery(
                "grant_type=authorization_code&code=" + request.getParameter("code") + "&redirect_uri=" + redirectUri);
        String url = "https://auth.ms.casicloud.com/1/oauth/token?";
        String get = HttpClient.doGet(url + sign);
        JSONObject data = JSONObject.parseObject(get);
        String token = data.getJSONObject("data").getString("access_token");
        token = URLEncoder.encode(token, "UTF-8");
        String userUrl = "https://auth.ms.casicloud.com/1/oauth/user_info?";
        String sign2 = SignUtil.signQuery("access_token=" + token);
        JSONObject userInfo = JSONObject.parseObject(HttpClient.doGet(userUrl + sign2));
        log.info("user ------> " + userInfo.toJSONString());
        String userName = userInfo.getJSONObject("data").getString("user_name");
        String userAccount = userInfo.getJSONObject("data").getString("user_account");
        boolean hasUser = userService.checkUserByShorturl(userAccount);
        if (hasUser) {
            User user = userService.findUserByShorturl(userAccount);
            userSessionUtils.setLoginMember(request, response, true, user);
            response.sendRedirect(webRedirect);
        } else {
            userService.addUserReg(4, userName, System.currentTimeMillis() + "", userAccount, null, request, response);
            response.sendRedirect(webRedirect);
        }
    }

}
